<?php

    /**
     * @author theodor-flavian hanu
     * Date: 5/24/14
     * Time: 10:13 AM
     */
    /**
     * StudentsController
     *
     * @package acatist
     * @author Boomer
     * @copyright 2014
     * @version $Id$
     * @access public
     */
    class StudentsController extends AppController {

        var $name = "Students";

        var $uses = array( "User", "RequirementValue", "Registration","Task");

        /**
         * @return bool
         */
        public function beforeFilter() {
            parent::beforeFilter();

            return true;
        }

        /**
         * @param null $user
         *
         * @return bool
         */
        public function isAuthorized( $user = null ) {
            if( isset( $user['tip'] ) && $user['tip'] == "student" ) {
                return true;
            }
            return false;
        }

        /**
         *
         */
        public function index() {
            $theme = $this->Theme->find('first',array('conditions'=>array('Theme.id_stud'=>$this->Auth->user('id'))) );
            if ($theme)
                $this->redirect(SITE_URL.'students/vizualizare_etape');
            else
                $this->redirect(SITE_URL.'students/alege_tema');
        }

        /**
         * @param null $id
         * Preia datele din formular si updateaza profilul pentru utilizatorul curent
         */
        public function editare_profil( $id = null ) {
            $this->User->id = $this->Auth->user( 'id' );
            if( $this->data == null ) {
                $this->data = $this->User->read();
            }
            if( $this->request->is( "post" ) ) {
                $do_not_update = array();
                if( $this->request->data["User"]['password'] == "" ) {
                    $this->User->validator()
                               ->remove( "password" );
                    $do_not_update[] = "password";
                }
                if( $this->User->save( $this->request->data, true, array_diff( array_keys( $this->User->schema() ), $do_not_update ) ) ) {
                    $this->Session->setFlash( "Updated", "flash_success" );
                }
                else {
                    $this->Session->setFlash( "Could not update! Please review your input and try again", "flash_error" );
                }
            }
        }

        /**
         *Extrage toate temele disponibile in functie de domeniile de iteres apoi trimie datele optinute carre view care le va afisa
         */
        public function alege_tema() {
            $subiecte_interes = $this->User->query( "SELECT subiecte_interes FROM users WHERE tip = 'profesor'" );
            $sub_int          = array();
            foreach( $subiecte_interes as $si ) {
                $sub_int = array_merge( $sub_int, explode( ",", $si['users']['subiecte_interes'] ) );
            }
            $this->set( "autocompleteAvailableTags", implode( '","', array_unique( $sub_int ) ) );
            $this->Paginator->settings['paramType'] = 'querystring';
            $this->Paginator->settings['limit']     = '25';
            $keyword                                = "";
            if( isset( $this->request->query['keyword'] ) ) {
                $keyword                                     = $this->request->query['keyword'];
                $keyword                                     = str_replace( " ", "", $keyword );
                $conditions                                  = array();
                $conditions["User.subiecte_interes REGEXP "] = ".*" . str_replace( ",", ".*|.*", $keyword ) . ".*";
                $this->Paginator->settings['conditions']     = $conditions;
            }
            $this->Paginator->settings['conditions']['User.tip'] = "profesor";
            $this->Paginator->settings['contain']                = array( "UnapprovedThemes" );
            $this->set( "keyword", $keyword );
            $this->set( "profs", $this->Paginator->paginate( 'User' ) );
        }

        /**
         * @param null $id
         * Salveaza in baza de date pentru tema cu id-ul primit ca parametru studentul care a aplicat
         */
        public function inscriere_tema( $id = null ) {
            $theme   = $this->Theme->find( 'first', array(
                "conditions" => array( "Theme.id" => $id ),
                "contain"    => "Requirement"
            ) );
            $user_id = $this->Auth->user( "id" );
            $registration=$this->Registration->find('first', array(
                "conditions" => array( "Registration.id_theme" => $id ,"Registration.id_user"=>$user_id),
                "recursive" =>-1
            ) );
            $ok=1;
            if(empty($registration)){
                $this->set( "user_id", $user_id );
                $this->set( "tema", $theme );
                $this->set("ok",$ok);
                $requirements = $theme['Requirement'];
                if( $this->request->is( "post" ) ) {
                    $doSave = true;
                    $toSave = array();
                    foreach( $requirements as $req ) {
                        if( $req['required'] == 1 && ( ! isset( $this->request->data['Requirement'][$req['id']] ) || "" == $this->request->data['Requirement'][$req['id']] ) ) {
                            $this->Session->setFlash( "Nu s-a putut finaliza cererea! Va rugam completati campurile obligatorii", "flash_error" );
                            $doSave = false;
                            break;
                        }
                        $toSave[] = array(
                            "id_requirement" => $req['id'],
                            "id_student"     => $user_id,
                            "value"          => is_array( $this->request->data['Requirement'][$req['id']] ) ? implode( ",", $this->request->data['Requirement'][$req['id']] ) : $this->request->data['Requirement'][$req['id']]
                        );
                    }
                    if( $doSave ) {
                        if( $this->RequirementValue->saveAll( $toSave ) ) {
                            $this->Registration->save( array(
                                                           "id_user"  => $user_id,
                                                           "id_prof"  => $theme['Theme']['id_user'],
                                                           "id_theme" => $id
                                                       ) );
                            $this->Session->setFlash( "Inscriere finalizata!", "flash_success" );
                        }
                        else {
                            $this->Session->setFlash( "Nu s-a putut finaliza inscrierea! Incercati din nou", "flash_error" );
                        }
                    }
                }
            }
            else{
                $ok=0;
                $this->set( "user_id", $user_id );
                $this->set( "tema", $theme );
                $this->set(  "ok",$ok);
                $requirements = $theme['Requirement'];
                $this->Session->setFlash( "Ati aplicat deja la aceasta tema!", "flash_error" );
            }
        }

        /**
         * Extrage din baza de Tema pentru studentul logat si etapele , apoi trimite datele catre view care le va afisa
         */
        public function vizualizare_etape () {
            $user_id = $this->Auth->user( "id" );
            $theme = $this->Theme->find('first',array('conditions'=>array('Theme.id_stud'=>$user_id)) );

            $etape = $this->Stage->find('all', array( 'conditions'=>array(
                'Stage.id_theme'=>$theme['Theme']['id']
            )
            ));
            $this->set("etape",$etape);
            $this->set("theme",$theme);
        }

        /**
         * @param $id_stage
         * Inregistreaza un upload de fisiere pentru etapa primita ca parametru
         */
        public function upload_file($id_stage) {
            $this->layout = 'ajax';
            $theme = $this->Theme->find('first',array('conditions'=>array('Theme.id_stud'=>$this->Auth->user('id'))) );
            $this->Extra->create(array(
                                     'id_user'=>$this->Auth->user('id'),
                                     'id_theme'=>$id_stage,
                                     //'id_stage'=>$id_stage,
                                     'name'=>substr($_FILES['file']['name'],0,strrpos($_FILES['file']['name'],'.')-1),
                                     'path'=>'',
                                     'description'=>'uploaded file',
                                 ));
            $this->Extra->save();
            $id = $this->Extra->getLastInsertID();

            $ext = substr($_FILES['file']['name'],strrpos($_FILES['file']['name'],'.'));
            $name = $id.$ext;
            $path = 'files/'.$name;
            move_uploaded_file($_FILES['file']['tmp_name'],$path);
            
            $this->Extra->set(array(
                'path'=>$path,
                'id' => $id
            ));
            $this->Extra->save();

        }

    }